#include "mvdwindow.h"
#include "ui_mvdwindow.h"

MvdWindow::MvdWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MvdWindow)
{
    ui->setupUi(this);
    connect(ui->widget, &DBSetWindow::databaseOpened, this, &MvdWindow::initWindow);

    // 在构造函数中连接查询信号和槽
    connect(ui->pushButton_3, &QPushButton::clicked, this, &MvdWindow::sortData);
}

MvdWindow::~MvdWindow()
{
    delete ui;
}

void MvdWindow::initWindow(QSqlDatabase &db)
{
    /*
     * 1、实例化模型
     * 2、(model)模型关联数据源（data)
     * 3、视图关联模型
     */

    //    QStringListModel * smodel = new QStringListModel(this);
    //    QStringList sl;
    //    sl<<"aaa"<<"bbb"<<"ccc";
    //    smodel->setStringList(sl);
    //    QFileSystemModel* fmodel = new QFileSystemModel(this);
    //    fmodel->setRootPath(QDir::rootPath());
    //    ui->tableView->setModel(fmodel);
    //    ui->treeView->setModel(fmodel);
    //    ui->listView->setModel(fmodel);
    //    ui->columnView->setModel(fmodel);

    if (!db.isOpen()) {
            if (!db.open()) {
                QMessageBox::critical(this, tr("Database Error"),
                                      tr("Failed to connect to the database: %1").arg(db.lastError().text()));
                return; // 连接失败，退出初始化
            }
        }

        // 实例化模型并设置表
        tmodel = new QSqlTableModel(this);
        tmodel->setTable("chargelog");
        if (!tmodel->select()) {
            QMessageBox::critical(this, tr("Database Error"),
                                  tr("Failed to select data from table: %1").arg(tmodel->lastError().text()));
            return; // 选择数据失败，退出初始化
        }


        ui->tableView->setModel(tmodel);
        tmodel->setEditStrategy(QSqlTableModel::OnManualSubmit);
        ui->tableView->setItemDelegateForColumn(0, new CustomDelegate);
}

bool MvdWindow::isDatabaseOpen() {
    return tmodel && tmodel->database().isOpen();
}

void MvdWindow::on_addDbAction_triggered()
{
    if (!isDatabaseOpen()) {
        QMessageBox::warning(this, tr("Warning"), tr("Database is not open. Please connect to the database."));
        return; // 数据库未打开，返回
    }

    QSqlRecord emptyRec = tmodel->record();
    int row = tmodel->rowCount();
    tmodel->insertRecord(row, emptyRec);
}

void MvdWindow::on_delDbAction_triggered()
{
    if (!isDatabaseOpen()) {
        QMessageBox::warning(this, tr("Warning"), tr("Database is not open. Please connect to the database."));
        return; // 数据库未打开，返回
    }

    tmodel->removeRow(ui->tableView->currentIndex().row());
}

void MvdWindow::on_updateDbAction_triggered()
{
    if (!isDatabaseOpen()) {
        QMessageBox::warning(this, tr("Warning"), tr("Database is not open. Please connect to the database."));
        return; // 数据库未打开，返回
    }

    tmodel->submitAll();
}

void MvdWindow::on_refreshDbAction_triggered()
{
    if (!isDatabaseOpen()) {
        QMessageBox::warning(this, tr("Warning"), tr("Database is not open. Please connect to the database."));
        return; // 数据库未打开，返回
    }

    tmodel->select();
}

void MvdWindow::on_reDbAction_triggered()
{
    if (!isDatabaseOpen()) {
        QMessageBox::warning(this, tr("Warning"), tr("Database is not open. Please connect to the database."));
        return; // 数据库未打开，返回
    }

    tmodel->revertAll();
}

void MvdWindow::on_sumbitDbAction_triggered()
{
    if (!isDatabaseOpen()) {
        QMessageBox::warning(this, tr("Warning"), tr("Database is not open. Please connect to the database."));
        return; // 数据库未打开，返回
    }

    tmodel->submitAll();
}

void MvdWindow::on_excelButton_clicked()
{
    QString filePath = QFileDialog::getSaveFileName(this, tr("Save PDF"), "", tr("PDF Files (*.pdf)"));
    if (filePath.isEmpty()) {
        return; // 用户取消操作
    }

    QPrinter printer(QPrinter::HighResolution);
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName(filePath);

    QTextDocument doc;

    // 创建 PDF 文档内容
    QString html = "<h1>Chargelog Data</h1><table border=\"1\">";
    for (int row = 0; row < tmodel->rowCount(); ++row) {
        html += "<tr>";
        for (int col = 0; col < tmodel->columnCount(); ++col) {
            html += "<td>" + tmodel->data(tmodel->index(row, col)).toString() + "</td>";
        }
        html += "</tr>";
    }
    html += "</table>";

    doc.setHtml(html);
    doc.print(&printer);
}

void MvdWindow::on_pdfButton_clicked()
{
        QString filePath = QFileDialog::getSaveFileName(this, tr("Save Excel"), "", tr("Excel Files (*.xlsx)"));
        if (filePath.isEmpty()) {
            return; // 用户取消操作
        }

        QXlsx::Document xlsx;

        // 写入数据
        for (int row = 0; row < tmodel->rowCount(); ++row) {
            for (int col = 0; col < tmodel->columnCount(); ++col) {
                xlsx.write(row + 1, col + 1, tmodel->data(tmodel->index(row, col)).toString());
            }
        }

        // 保存文件
        xlsx.saveAs(filePath);
}

void MvdWindow::sortData() {
    if (!isDatabaseOpen()) {
        QMessageBox::warning(this, tr("Warning"), tr("Database is not open. Please connect to the database."));
        return; // 数据库未打开，返回
    }

    QString selectedSort = ui->comboBox->currentText();

    if (selectedSort == "chargingID") {
        ui->lineEdit->setEnabled(true); // 启用文本框
        ui->lineEdit->clear(); // 确保输入框清空

        QString inputValue = ui->lineEdit->text();
        if (inputValue.isEmpty()) {
            QMessageBox::warning(this, tr("Warning"), tr("Please enter a value for chargingID."));
            return; // 如果用户没有输入值，则返回
        }

        tmodel->setFilter(QString("chargingID = '%1'").arg(inputValue));
        tmodel->select(); // 应用过滤条件

        tmodel->setSort(tmodel->fieldIndex("chargingID"), Qt::AscendingOrder);
    } else {
        ui->lineEdit->setEnabled(false); // 禁用文本框
        ui->lineEdit->clear(); // 清除输入框中的内容
        tmodel->setFilter(""); // 清除过滤条件

        if (selectedSort == "nowTime") {
            tmodel->setSort(tmodel->fieldIndex("nowTime"), Qt::AscendingOrder);
        } else if (selectedSort == "chargingTime") {
            tmodel->setSort(tmodel->fieldIndex("chargingTime"), Qt::AscendingOrder);
        } else if (selectedSort == "cost") {
            tmodel->setSort(tmodel->fieldIndex("cost"), Qt::AscendingOrder);
        }
    }

    tmodel->select();
}




